package com.zdya.combatdocuments.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zdya.combatdocuments.entity.Authorization;
import com.zdya.combatdocuments.entity.User;
import com.zdya.combatdocuments.entity.vo.AuthorizationVo;
import com.zdya.combatdocuments.entity.vo.ResultVo;
import com.zdya.combatdocuments.service.AuthorizationService;
import com.zdya.combatdocuments.service.UserService;
import com.zdya.combatdocuments.util.AESUtils;

import com.zdya.combatdocuments.util.SerialNumberUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/documents/authorization")
@Api(tags = "授权",description = "授权接口")
public class AuthorizationController {

    @Autowired
    private AuthorizationService authorizationService;

    @Autowired
    private UserService userService;


    @ApiOperation(value = "新建授权",httpMethod = "POST")
    @ApiImplicitParam(name = "Authorization",value = "新建授权信息，JSON格式")
    @PostMapping("/save")
    public ResultVo<Object> save(@RequestBody AuthorizationVo authorizationEntity){
        return authorizationService.saveAuthor(authorizationEntity);
    }


    @ApiOperation(value = "条件查询",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization",value = "新建授权信息，JSON格式"),
            @ApiImplicitParam(name = "pageNo",value = "页码"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数")
    })
    @GetMapping("/getAuthor")
    public ResultVo<IPage<Authorization>> getAuthor(Integer pageNo, Integer pageSize ,Authorization authorizationEntity){
        return authorizationService.getAuthorPage(pageNo,pageSize,authorizationEntity);
    }


    @ApiOperation(value = "下载授权文件",httpMethod = "GET")
    @GetMapping("/download/{id}")
    public void download(HttpServletResponse response,@PathVariable("id") Long id) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/plain");
            Authorization authorizationEntity = authorizationService.getById(id);
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, "admin"));
            authorizationEntity.setAuthorName(user.getName());
            Map<String, String> allSn = SerialNumberUtil.getAllSn();
            String cpuid = allSn.get("cpuid");
            authorizationEntity.setAuthorCpu(cpuid);
            //设置响应头,让浏览器下载而不是打开 downloadName是下载下来之后的文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + authorizationEntity.getUsername()+".lce");
            BufferedOutputStream buff=null;
            ServletOutputStream out=null;
            try {
                out= response.getOutputStream();
                buff= new BufferedOutputStream(out);
                String s = JSON.toJSONString(authorizationEntity);
                String encrypt = AESUtils.encrypt(s, "1234567891011121");
                buff.write(encrypt.getBytes("UTF-8"));
                buff.flush();
                buff.close();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    buff.close();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "从节点申请授权",httpMethod = "POST")
    @PostMapping("/applyAuthor")
    public ResultVo<Object> applyAuthor(@RequestBody AuthorizationVo authorizationVo){
        return authorizationService.applyAuthor(authorizationVo.getPrimaryIp(),authorizationVo);
    }

    @ApiOperation(value = "从节点接受授权文件",httpMethod = "POST")
    @PostMapping("/acceptAuthorFile")
    public ResultVo<Object> acceptAuthorFile(@RequestParam("authorFile") MultipartFile authorFile, @RequestParam("primaryIp") String primaryIp,
                                             @RequestParam("username") String username) throws IOException {
        return authorizationService.acceptAuthorFile(authorFile, primaryIp, username);
    }

    @ApiOperation(value = "主节点接收申请",httpMethod = "POST")
    @PostMapping("/acceptAuthor")
    public ResultVo<Object> acceptAuthor(@RequestBody AuthorizationVo authorizationVo){
        return authorizationService.acceptAuthor(authorizationVo);
    }

    @ApiOperation(value = "主节点审批",httpMethod = "POST")
    @PostMapping("/approvalAuthor")
    public ResultVo<Object> approvalAuthor(@RequestParam("id") Long id){
        return authorizationService.approvalAuthor(id);
    }

    @ApiOperation(value = "查询待授权信息",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization",value = "查询待授权信息，JSON格式"),
            @ApiImplicitParam(name = "pageNo",value = "页码"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数")
    })
    @GetMapping("/getAuthorizations")
    public ResultVo<IPage<Authorization>> getAuthorizations(Integer pageNo, Integer pageSize ,Authorization authorizationEntity){
        return authorizationService.getAuthorizations(pageNo,pageSize,authorizationEntity);
    }


}
